package com.example.data.factory.web1.controller;

import com.example.data.factory.common.Dto.InsertDictDataDto;
import com.example.data.factory.common.Dto.InsertDictDto;
import com.example.data.factory.entity.entity.DictExcelHeaderData;
import com.example.data.factory.service.service.DictDataService;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

@RestController
public class DictExcelController {
    @Resource
    private DictDataService dictDataService;
    private void processUserData(List<DictExcelHeaderData> dataList) {
        for (DictExcelHeaderData data : dataList) {
            // 创建InsertDictDto对象并填充数据
            InsertDictDto insertDictDto = new InsertDictDto();
            insertDictDto.setDictName(data.getCodeTableName());
            insertDictDto.setDescription(data.getCodeTableDescription());

            // 创建单个DictData DTO
            InsertDictDataDto dictDataDto = new InsertDictDataDto();
            dictDataDto.setDictLabel(data.getCodeName());
            dictDataDto.setDictValue(data.getCodeValue());
            dictDataDto.setDescription(data.getCodeMeaning()); // 假设getCodeMeaning对应于description

            // 将DictData DTO添加到列表中
            List<InsertDictDataDto> dictDataDtos = new ArrayList<>();
            dictDataDtos.add(dictDataDto);

            // 设置到InsertDictDto对象中
            insertDictDto.setDictDataDtos(dictDataDtos);

            // 调用服务层方法保存DictData
            dictDataService.saveDictData(insertDictDto);
        }
    }
    @GetMapping("/exportDict")
    public ResponseEntity<byte[]> exportExcel() {
        String fileName = "码表模板.xlsx"; // 文件名与模板一致
        byte[] bytes = exportToExcel();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", fileName);

        return ResponseEntity.ok()
                .headers(headers)
                .body(bytes);
    }

    private byte[] exportToExcel() {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Sheet1"); // 工作表名称与模板一致

        // ================= 表头设计 =================
        // 创建第一行表头
        Row headerRow1 = sheet.createRow(0);
        createHeaderCell(workbook, headerRow1, 0, "码表名称");
        createHeaderCell(workbook, headerRow1, 1, "码表说明");
        createHeaderCell(workbook, headerRow1, 2, "编码信息");

        // 合并编码信息单元格（C到E列）
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 2, 4));

        // 创建第二行表头
        Row headerRow2 = sheet.createRow(1);
        createHeaderCell(workbook, headerRow2, 2, "编码取值");
        createHeaderCell(workbook, headerRow2, 3, "编码名称");
        createHeaderCell(workbook, headerRow2, 4, "编码含义");

        // 合并码表名称和码表说明的垂直单元格
        sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 0)); // A列合并
        sheet.addMergedRegion(new CellRangeAddress(0, 1, 1, 1)); // B列合并

        // ================= 列宽自适应 =================
        sheet.setColumnWidth(0, 4000); // 码表名称列宽
        sheet.setColumnWidth(1, 5000); // 码表说明列宽
        sheet.setColumnWidth(2, 3000); // 编码取值列宽
        sheet.setColumnWidth(3, 4000); // 编码名称列宽
        sheet.setColumnWidth(4, 6000); // 编码含义列宽

        // ================= 输出文件 =================
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            workbook.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                workbook.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return out.toByteArray();
    }

    private void createHeaderCell(Workbook workbook, Row row, int columnIndex, String value) {
        CellStyle headerStyle = workbook.createCellStyle();
        headerStyle.setAlignment(HorizontalAlignment.CENTER);
        headerStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 加粗字体
        Font font = workbook.createFont();
        font.setBold(true);
        headerStyle.setFont(font);

        // 加粗边框（将THIN改为MEDIUM）
        headerStyle.setBorderTop(BorderStyle.MEDIUM);    // 上边框
        headerStyle.setBorderBottom(BorderStyle.MEDIUM); // 下边框
        headerStyle.setBorderLeft(BorderStyle.MEDIUM);   // 左边框
        headerStyle.setBorderRight(BorderStyle.MEDIUM);  // 右边框

        Cell cell = row.createCell(columnIndex);
        cell.setCellValue(value);
        cell.setCellStyle(headerStyle);
    }
    @PostMapping("/importDict")
    public String importExcel(@RequestParam("file") MultipartFile file) {
        try (InputStream inputStream = file.getInputStream()) {
            List<DictExcelHeaderData> dataList = new ArrayList<>();
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> iterator = sheet.iterator();

            // 跳过表头
            if (iterator.hasNext()) {
                iterator.next(); // 跳过第一行表头
            }

            while (iterator.hasNext()) {
                Row row = iterator.next();
                DictExcelHeaderData data = new DictExcelHeaderData();

                Cell cell;

                // 获取码表名称
                cell = row.getCell(0);
                String codeTableName = cell != null ? cell.getStringCellValue() : "";
                data.setCodeTableName(codeTableName);

                // 获取码表说明
                cell = row.getCell(1);
                String codeTableDescription = cell != null ? cell.getStringCellValue() : "";
                data.setCodeTableDescription(codeTableDescription);

                // 获取编码取值
                cell = row.getCell(2);
                String codeValue;
                if (cell != null) {
                    switch (cell.getCellType()) {
                        case STRING:
                            codeValue = cell.getStringCellValue();
                            break;
                        case NUMERIC:
                            codeValue = String.valueOf((int)cell.getNumericCellValue());
                            break;
                        default:
                            codeValue = ""; // 或者设置为其他默认值
                    }
                } else {
                    codeValue = "";
                }
                data.setCodeValue(codeValue);

                // 获取编码名称
                cell = row.getCell(3);
                String codeName = cell != null ? cell.getStringCellValue() : "";
                data.setCodeName(codeName);

                // 获取编码含义
                cell = row.getCell(4);
                String codeMeaning = cell != null ? cell.getStringCellValue() : "";
                data.setCodeMeaning(codeMeaning);

                dataList.add(data);
            }

            // 处理导入的数据，通过调用新增接口保存到数据库
            processUserData(dataList);

            return "导入成功，共导入 " + dataList.size() + " 条数据";
        } catch (IOException e) {
            e.printStackTrace();
            return "导入失败: " + e.getMessage();
        }
    }
}